# @Time : 2024-11-07 9:33
# @Author : Fioman 
# @Phone : 13149920693
"""
running(): 如果该Future正在运行且不可取消的时候返回True,否则返回False.
done(): 如果该Future任务被取消或者是执行完成,则该方法返回True.
"""
import threading
import time
from concurrent.futures import ThreadPoolExecutor, wait

"""
代码逻辑:
1) 创建10个任务
2) 每个任务休眠一定的时间,然后结束
3) 过2秒之后,取消任务,然后去检查哪些任务结束了,哪些任务还在运行,哪些任务结束了.
"""


def task_sleep(seconds):
    threadName = threading.current_thread().name
    print(f"{threadName} 开始")
    time.sleep(seconds)
    print(f"{threadName} 结束")
    return seconds


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=5, thread_name_prefix="task_") as executor:
        futures = [executor.submit(task_sleep, i) for i in range(1, 11)]
        time.sleep(2)
        results = []
        for future in futures:
            if not future.running():
                print("future 取消了")
                future.cancel()  # 取消的时候有可能会取消失败的.
                if future.cancelled():
                    print("future 取消成功")
                else:
                    print("future 取消失败")
        wait(futures)
        for future in futures:
            if not future.cancelled() and future.done():
                results.append(future.result())
        print("results = {}".format(results))
